# -*- coding:utf-8 -*-
from tornado import web, gen
import hashlib
import urllib
from appcommon.framework import APIRequestHandler
from appcommon import checktool
from common import decorator
from common import utiltool
from common import timetool
import models as wechatm
from user import models as userm
import time
import re

import xml.etree.ElementTree as ET


class WechatHandler(APIRequestHandler):
    @gen.coroutine
    def get(self):
        sToken = "qichengjiakaojiaogui2017"
        sEncodingAESKey = "qU3YAPe8WLk483H62oJf8w4ibAsH3oGUK6xZyp4rRuO"
        sCorpID = "wxce3ced320373d100"
        sVerifyMsgSig = urllib.unquote(self.get_argument('signature', ''))
        sVerifyTimeStamp = urllib.unquote(self.get_argument('timestamp', ''))
        sVerifyNonce = urllib.unquote(self.get_argument('nonce', ''))
        sVerifyEchoStr = urllib.unquote(self.get_argument('echostr', u''))

        sortlist = [sToken, sVerifyTimeStamp, sVerifyNonce]
        sortlist.sort()
        sha = hashlib.sha1()
        sha.update("".join(sortlist))
        sha.hexdigest()
        if sha.hexdigest() != sVerifyMsgSig:
            self.write(u'')
            self.finish()
        else:
            self.write(sVerifyEchoStr)
            self.finish()

    @gen.coroutine
    def post(self):

        sToken = "qichengjiakaojiaogui2017"
        sEncodingAESKey = "qU3YAPe8WLk483H62oJf8w4ibAsH3oGUK6xZyp4rRuO"
        sCorpID = "wxce3ced320373d100"

        sReqMsgSig = urllib.unquote(self.get_argument('signature', ''))
        sReqTimeStamp = urllib.unquote(self.get_argument('timestamp', ''))
        sReqNonce = urllib.unquote(self.get_argument('nonce', ''))
        openid = urllib.unquote(self.get_argument('openid', ''))
        sReqData = self.request.body
        print sReqData
        # 检验消息的真实性，并且获取解密后的明文
        sortlist = [sToken, sReqTimeStamp, sReqNonce]
        sortlist.sort()
        sha = hashlib.sha1()
        sha.update("".join(sortlist))
        sign = sha.hexdigest()
        if sign != sReqMsgSig:
            self.write(u'')
            self.finish()
        else:
            data = ET.fromstring(sReqData)
            msgtype = data.find('MsgType').text
            if msgtype == 'event':
                # event_type = data.find('Event').text
                # if event_type == 'subscribe':
                #     out = ""
                # else:
                #     out = ""
                out = ""
            else:
                tousername = data.find('ToUserName').text
                fromusername = data.find('FromUserName').text
                out = wechatm.create_response(fromusername, tousername)

            self.write(out)
            self.finish()
